package edu.langnan.xiaoli.config.security.service;

import edu.langnan.xiaoli.config.security.LoginUser;
import edu.langnan.xiaoli.core.domain.StudentDO;
import edu.langnan.xiaoli.service.StudentService;
import edu.langnan.xiaoli.service.impl.PermissionService;
import edu.langnan.xiaoli.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author cql
 */
@Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private StudentService studentService;

    @Autowired
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String stuNo) throws UsernameNotFoundException {
        StudentDO student = studentService.findStudentByStuNo(stuNo);
        if (StringUtils.isNull(student)) {
            log.info("登录学号：{} 不存在.", stuNo);
            throw new UsernameNotFoundException("登录用户：" + stuNo + " 不存在");
        }
        return createLoginUser(student);
    }

    public UserDetails createLoginUser(StudentDO student) {

        /**
         * 查询角色信息
         */
        Set<String> roles = permissionService.getRoleOfStudent(student.getId());

        /**
         * 查询权限信息
         */
        Set<String> perms = permissionService.getPermOfStudent(student.getId());
        LoginUser loginUser = new LoginUser(student, perms, roles);

        return loginUser;
    }


}
